# -*- coding: utf-8 -*-
"""
******* 文档说明 ******
API 调用Demo

# 当前项目: API-Demo
# 创建时间: 2019-08-04  12:29
# 开发作者: vincent
# 创建平台: PyCharm
# 版   本: V1.0
"""
import json
import requests
import numpy as np
import cv2
import base64
import hashlib


class API(object):

    def __init__(self, api_uri, debug=True):
        """
        :param api_uri:  API 请求路径
        :param debug:    Debug 开关
        """
        self.api_uri = api_uri
        self.debug = debug

    def __call__(self, image_np):
        """
        :param image_np:  请求图片 numpy 格式 cv2.imdecode()
        :return:
        """
        image_data = base64.b64encode(image_np)  # 图片数据转换成Base64传输

        # 传输图片Hash值
        image_hash = hashlib.md5(image_data).hexdigest()

        # 图片大小
        image_height, image_width, image_channl = image_np.shape
        params = {'ImageHeight': image_height,
                  'ImageWidth': image_width,
                  'ImageChannl': image_channl
                  }

        try:
            # API 请求命令
            api_response = requests.post(self.api_uri, params=params, data=image_data)
            # print('{:12s}: {}'.format('URL', api_response.url))
            # print('{:12s}: {}'.format('Path_URL', api_response.request.path_url))
            # print('{:12s}: {}'.format('StatusCode', api_response.status_code))
            # print('{:12s}: {}'.format('Method', api_response.request.method))
            # print('{:12s}: {}'.format('Encoding', api_response.encoding))
            # print('{:12s}: {}'.format('Headers', api_response.headers))
            # print('{:12s}: {}'.format('Body', api_response.request.body))
            # print('{:12s}: {}'.format('Cookies', api_response.cookies))
            # print('{:12s}: {}'.format('Content', api_response.content))
            # print('{:12s}: {}'.format('Text', api_response.text))

            # 解析返回字符串
            response_json = json.loads(api_response.text, encoding='utf-8')

            # Hash 值校验成功
            if response_json['ImageHash'] == image_hash:
                result_json = {'Status': 'Success',
                               'Information': 'Success',
                               'API_Result': response_json
                               }
            # Hash 值校验失败
            else:
                result_json = {'Status': 'Fail',
                               'Information': 'Hash Verification failed!',
                               'API_Result': response_json
                               }
        # 异常
        except Exception as error:
            print('Error:{}'.format(repr(error)))
            result_json = {'Status': 'Fail',
                           'Information': repr(error)}

        if self.debug:
            print('-----------------------------------------------------')
            print('API URI:{}'.format(self.api_uri))
            print('ImageShape:{}'.format(params))
            print('ImageHash:{}'.format(image_hash))
            print('API_Result:\n{}'.format(result_json))
            print('-----------------------------------------------------')

        return result_json


if __name__ == '__main__':
    # TODO 初始化API
    api = API(api_uri='http://0.0.0.0:5588/test', debug=True)

    # 请求数据
    img_path = '/home/vincent/Project/API-Demo/_data/1.jpg'
    # 读取图片数据
    image = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), cv2.IMREAD_COLOR)

    import time
    start_time = time.time()

    # TODO API 调用
    api(image)

    print(time.time() - start_time)
